package com.atguigu.gmall.pay.api;

import com.alipay.api.AlipayApiException;
import com.alipay.api.request.AlipayTradeQueryRequest;
import com.atguigu.gmall.feign.order.OrderFeignClient;
import com.atguigu.gmall.model.order.OrderInfo;
import com.atguigu.gmall.pay.service.PayService;
import com.atguigu.gmall.pay.vo.PayParamsVo;
import com.fasterxml.jackson.core.JsonProcessingException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.text.SimpleDateFormat;
import java.util.Date;

@RequestMapping("/api/payment")
@RestController
public class PayController {

    @Autowired
    PayService payService;

    @Autowired
    OrderFeignClient orderFeignClient;

    /**
     * 去查询支付宝是否已经支付了
     * 1：代表支付成功
     * 0：其他状态
     * @param outTradeNo
     * @return
     */
    @GetMapping("/status/{outTradeNo}")
    public String queryOrderPayStatus(@PathVariable("outTradeNo") String outTradeNo) throws JsonProcessingException, AlipayApiException {

        Boolean b = payService.queryOrderPayStatus(outTradeNo);

        return b?"1":"0";
    }


    @GetMapping("/alipay/submit/{orderId}")
    public String payment(@PathVariable("orderId") Long orderId) throws JsonProcessingException, AlipayApiException {
        PayParamsVo payParamsVo = new PayParamsVo();
        //封装订单数据
        OrderInfo orderById = orderFeignClient.getOrderById(orderId);
        payParamsVo.setTotal_amount(orderById.getTotalAmount().toString());
        payParamsVo.setOut_trade_no(orderById.getOutTradeNo());
        payParamsVo.setSubject(orderById.getConsignee() + "的订单");
        payParamsVo.setBody(orderById.getOrderComment());
        //TODO 支付宝过期收单
        Date expireTime = orderById.getExpireTime();
        //设置支付宝订单过期时间 和mq队列的超时时间相同，两头过期，保证临界值，订单过期了还能再支付
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        payParamsVo.setTime_expire(format.format(expireTime));

        //调用支付
        String result = payService.payOrder(payParamsVo);

        return result;

    }

}
